<template>

    <el-dialog v-model="open" :title="title" width="700" :close-on-click-modal="false">
        <el-form ref="formRef" :model="form" label-width="100px">
            <el-form-item label="系列名称" prop="title" :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                <el-input v-model="form.title" placeholder="请输入系列名称" />
            </el-form-item>
            <el-form-item label="锻炼类型" prop="typeName"
                :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                <el-tree-select v-model="form.typeName" :data="typeTree"
                    :props="{ label: 'label', children: 'children', disabled: 'disabled' }" :render-after-expand="false"
                    node-key="typeId" default-expand-all @nodeClick="handleNodeClick" style="width: 240px" />
            </el-form-item>

            <el-form-item label="锻炼时长" prop="time" :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                <el-input v-model="form.time" placeholder="请输入锻炼时长">
                    <template #append>(分钟)</template>
                </el-input>
            </el-form-item>

            <el-form-item label="能量消耗" prop="consume" :rules="[ { required: true, message: '该值不能为空', trigger: 'blur'}]">
                <el-input v-model="form.consume" placeholder="请输入能量消耗">
                    <template #append>(千卡)</template>
                </el-input>
            </el-form-item>
            <el-form-item label="所需设备" prop="equip">
                <el-input v-model="form.equip" type="textarea" placeholder="请输入所需设备" />
            </el-form-item>
            <el-form-item label="锻炼焦点" prop="focus">
                <el-input v-model="form.focus" type="textarea" placeholder="请输入锻炼焦点" />
            </el-form-item>
            <el-form-item label="封面图片" prop="path">
                <el-upload class="avatar-uploader" :action="imageUploadUrl" :headers="data.header" :data="data.ossdata"
                    name="imgFile" :show-file-list="false" :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="form.path" :src="form.path" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>

</template>

<script lang="ts" setup>
    import { ref, reactive } from 'vue';
    import { ExerciseSeriesResp } from '@/types/app/exercise'
    import { ElMessage, type FormInstance } from 'element-plus'
    import { updateSeries, addSeries, getSeries } from '@/api/app/exercise'
    import { getToken } from '@/utils/auth';

    //得到数据表单form样式对象
    const formRef = ref<FormInstance>();

    defineProps({
        typeTree: Object
    })

    //声明子组件的自定义事件 https://cn.vuejs.org/api/sfc-script-setup.html#defineprops-defineemits
    const emit = defineEmits(['refreshDataList'])

    //图片上传地址
    const imageUploadUrl = ref(import.meta.env.VITE_APP_BASE_API + '/oss/uploadImg');
    const token = getToken();
    //配置请求头的令牌
    // const header = {
    //     header: {
    //         'Authorization': token
    //     }
    // };

    //自己的定义额外参数
    const data = reactive({
        header: {
            'Authorization': token
        },
        ossdata: {
            fatherPath: 'images'
        }
    });

    const form = ref<ExerciseSeriesResp>({
        seriesId: undefined,
        title: "",
        tid: undefined,
        typeName: '',
        path: "",
        time: undefined,
        consume: undefined,
        equip: "",
        focus: ""
    })

    // 对话框配置
    const open = ref(false);
    const title = ref('');

    //对话框保存按钮
    const submitForm = () => {
        formRef.value?.validate((valid : boolean) => {
            // 验证不成功
            if (!valid) {
                return false
            }

            // 修改
            if (form.value.seriesId) {
                updateSeries(form.value).then(() => {
                    ElMessage.success({
                        message: '修改成功',
                        duration: 500,
                        onClose: () => {
                            // 关闭对话框
                            open.value = false
                            //调用重新查询数据操作
                            emit('refreshDataList')
                        }
                    });

                })
            } else {
                //新增
                addSeries(form.value).then(() => {
                    ElMessage.success({
                        message: '新增成功',
                        duration: 500,
                        onClose: () => {
                            // 关闭对话框
                            open.value = false
                            //调用重新查询数据操作
                            emit('refreshDataList')
                        }
                    });

                })
            }

        })

    };

    //对话框取消按钮
    const cancel = () => {
        open.value = false;
        resetFrom();
    };


    // 重置表单
    const resetFrom = () => {
        // 清空表单样式
        if (formRef.value) {
            formRef.value.resetFields();
        }
        // 重置值
        form.value = {
            seriesId: undefined,
            title: "",
            tid: undefined,
            path: "",
            time: undefined,
            consume: undefined,
            equip: "",
            focus: ""
        };
    };

    //判断如果是修改操作，就要查询数据库，还原数据,要暴露出去
    const init = (id ?: number) => {
        open.value = true
        // 重置表单数据
        resetFrom();
        // id 存在则为修改
        title.value = "锻炼系列-新增"
        if (id) {
            title.value = "锻炼系列-编辑"
            getSeries(id).then(resp => {
                const data : ExerciseSeriesResp = resp.data;
                //转换为字符串{"seriesId":1}
                const str = JSON.stringify(data);
                //再一次把字符串还原成对象
                form.value = JSON.parse(str);
            })
        }
    }

    // 上传图片时检查
    function beforeAvatarUpload(file : { type : string; size : number; }) {
        //允许的图片类型
        const imgType = (file.type === 'image/jpeg') || (file.type === 'image/png') || (file.type === 'image/gif');
        //文件大小3M
        const imgLimit = (file.size / 1024 / 1024) < 3;
        if (!imgType) {
            ElMessage.error("只允许jpg、png、gif格式的图片");
            return false;
        }
        if (!imgLimit) {
            ElMessage.error("上传的图片大小不能超过3MB");
            return false;
        }

        return true;
    }

    /** 上传图片 */
    function handleAvatarSuccess(res : { data : string | undefined; }, _file : any) {
        form.value.path = res.data;
    };

    /** 节点单击事件 */
    function handleNodeClick(data : any) {
        form.value.tid = data.typeId;
        form.value.typeName = data.label
    }

    //https://cn.vuejs.org/api/sfc-script-setup.html#defineexpose
    defineExpose({
        init
    })
</script>

<style scoped>
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
        /* object-fit: contain; */
        object-fit: cover;
    }
</style>

<style>
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
</style>
